<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[2, 5, 10, 20]"
                :page-size="pageParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit? '编辑':'新增'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <el-form v-if="showDialog" ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="doOut">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>

import { getRolesList, addRolesList, updateRolesList, deleteRole } from '@/api/settings'

export default {
  data() {
    return {
      isEdit: false, // false 新增   true 编辑
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '请添加角色描述', trigger: 'blur' }]
      },
      roleForm: {
        name: '',
        description: ''
      },
      list: [],
      pageParams: {
        page: 1, // 显示第几页
        pagesize: 2 // 每页有多少条数据
      },
      total: 0, // 数据总数
      showDialog: false
    }
  },
  created() {
    this.loadRolesList()
  },
  methods: {
    async doDel(id) {
      try {
        const res = await deleteRole(id)
        console.log(res)
        // 1. 提示
        this.$message.success('删除成功')
        // 2. 重新请求
        this.loadRolesList()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    // 用户点击了删除
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送请求删除
        this.doDel(id)
        if (this.list.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        // 重新渲染
        this.loadRolesList()
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 重置表单
    hClose() {
      this.$refs.roleForm.resetFields()
      this.roleForm = { // 表单数据项
        name: '',
        description: ''
      }
    },
    // 取消按钮
    doOut() {
      this.showDialog = false
    },
    // 编辑
    hEdit(row) {
      this.isEdit = true
      this.showDialog = true
      // 将表格中获取到的数据填充到表单
      // 因为this.roleForm进行了表单的双向绑定 那么表单中的数据改变 this.roleForm也会发生改变
      // 而this.roleForm和传进来的data(表格的数据对象) 所以导致 表单的数据改变 表格中的数据也跟着改变
      // 解决的办法 : 使用浅拷贝
      this.roleForm = { ...row }
    },
    // 实现编辑
    async doEdit() {
      try {
        const res = await updateRolesList(this.roleForm)
        console.log(res, 'doEdit')
        // 重新渲染
        this.loadRolesList()
        // 关闭弹层
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    // 新增
    hAdd() {
      this.isEdit = false
      this.showDialog = true
    },
    // 实现新增
    async doAdd() {
      try {
        const res = await addRolesList(this.roleForm)
        console.log(res, 'doAdd')
        const maxPage = Math.ceil((this.total + 1) / this.pageParams.pagesize)
        this.pageParams.page = maxPage
        // 重新渲染
        this.loadRolesList()
        // 关闭弹层
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    hSubmit() {
      // 兜底校验
      this.$refs.roleForm.validate(valid => {
        if (!valid) return // 校验失败
        // this.doAdd()
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      // 实现切换每页多少数据
      this.pageParams.pagesize = val
      // 回到第一页
      this.pageParams.page = 1
      this.loadRolesList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      // 实现切换分页
      this.pageParams.page = val
      this.loadRolesList()
    },
    // 获取数据
    async loadRolesList() {
      try {
        const res = await getRolesList(this.pageParams)
        console.log(res, 'loadRolesList')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
